package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.example.service.WeixinUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class CheckController {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WeixinUserService weixinUserService;


    @GetMapping("/checkToken")
    public String checkToken(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp
            , @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) {
        log.info("开始校验此次消息是否来自微信服务器，param->signature:{},\ntimestamp:{},\nnonce:{},\nechostr:{}",
                signature, timestamp, nonce, echostr);
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息不合法
            return "消息不合法";
        }
        // 消息合法
        return echostr;
    }

    @PostMapping(value = "/checkToken")
    public String weixinMsg(@RequestBody String requestBody, @RequestParam("signature") String signature,
                            @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) {

        log.info("requestBody:{}", requestBody);
        log.info("signature:{}", signature);
        log.info("timestamp:{}", timestamp);
        log.info("nonce:{}", nonce);

        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息不合法
            return "消息不合法";
        }
        // 消息合法
        return weixinUserService.handleWeixinMsg(requestBody);

    }
}
